<template>
  <page-header-wrapper>
    <a-card :loading="loading" :bordered="false" :style="{ marginBottom: '24px' }">
      <a-table
        bordered
        :loading="memberLoading"
        :columns="columns"
        :dataSource="data"
        :pagination="false"
        size="small">
        <template v-for="(col, i) in ['name', 'workId']" :slot="col" slot-scope="text, record">
          <a-input
            :key="col"
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            :placeholder="columns[i].title"
            @change="(e) => handleInputChange(e.target.value, record.key, col)"
          />
          <template v-else>{{ text }}</template>
        </template>
        <template slot="department" slot-scope="text, record">
          <a-select
            style="margin: -5px 0; width: 100%"
            key="department"
            :value="text"
            v-if="record.editable"
            @change="(e) => handleInputChange(e, record.key, 'department')"
          >
            <a-select-option value="行政部"> 行政部 </a-select-option>
            <a-select-option value="it部门"> it部门 </a-select-option>
            <a-select-option value="财务部门"> 财务部门 </a-select-option>
          </a-select>
          <template v-else>{{ text }}</template>
        </template>
        <template slot="entry" slot-scope="text, record">
          <a-date-picker
            valueFormat="YYYY-MM-DD"
            v-if="record.editable"
            :value="text"
            @change="(e) => handleInputChange(e, record.key, 'entry')"
            style="width: 100%"/>
          <template v-else>{{ text }}</template>
        </template>
        <template slot="probation" slot-scope="text, record">
          <a-range-picker
            valueFormat="YYYY-MM-DD"
            style="width: 100%"
            v-if="record.editable"
            :value="text"
            @change="(e) => handleInputChange(e, record.key, 'probation')"/>
          <template v-else>{{ text|filterTimeFormat }}</template>
        </template>
        <template slot="operation" slot-scope="text, record">
          <template v-if="record.editable">
            <span v-if="record.isNew">
              <a @click="saveRow(record)">添加</a>
              <a-divider type="vertical" />
              <a-popconfirm title="是否要删除此行？" @confirm="remove(record.key)">
                <a>删除</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a @click="saveRow(record)">保存</a>
              <a-divider type="vertical" />
              <a @click="cancel(record.key)">取消</a>
            </span>
          </template>
          <span v-else>
            <a @click="toggle(record.key)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm title="是否要删除此行？" @confirm="remove(record.key)">
              <a>删除</a>
            </a-popconfirm>
          </span>
        </template>
      </a-table>
      <a-button
        style="width: 100%; margin-top: 16px; margin-bottom: 8px"
        type="dashed"
        icon="plus"
        @click="newMember"
      >新增成员</a-button
      </a-card>
    </a-card></page-header-wrapper>
</template>

<script>
export default {
  name: 'EditTable',
  data () {
    return {
      loading: true,
      memberLoading: false,
      // table
      columns: [
        {
          title: 'key',
          dataIndex: 'key',
          key: 'key',
          width: '3%',
          scopedSlots: { customRender: 'key' }
        },
        {
          title: '成员姓名',
          dataIndex: 'name',
          key: 'name',
          width: '10%',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '工号',
          dataIndex: 'workId',
          key: 'workId',
          width: '10%',
          scopedSlots: { customRender: 'workId' }
        },
        {
          title: '所属部门',
          dataIndex: 'department',
          key: 'department',
          width: '10%',
          scopedSlots: { customRender: 'department' }
        },
        {
          title: '入职时间',
          dataIndex: 'entry',
          key: 'entry',
          width: '10%',
          scopedSlots: { customRender: 'entry' }
        },
        {
          title: '试用时间',
          dataIndex: 'probation',
          key: 'probation',
          width: '15%',
          scopedSlots: { customRender: 'probation' }
        },
        {
          title: '操作',
          key: 'operation',
          width: '25%',
          // fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      data: [
        {
          key: '1',
          name: '小明',
          workId: '001',
          editable: false,
          department: '行政部',
          entry: '2021-6-20',
          probation: ['2021-06-20', '2021-07-20']
        },
        {
          key: '2',
          name: '李莉',
          workId: '002',
          editable: false,
          department: 'IT部',
          entry: '2021-6-20',
          probation: ['2021-06-20', '2021-07-20']
        },
        {
          key: '3',
          name: '王小帅',
          workId: '003',
          editable: false,
          department: '财务部',
          entry: '2021-6-20',
          probation: ['2021-06-20', '2021-07-20']
        }
      ]
    }
  },
  filters: {
    filterTimeFormat (val) {
      if (val) {
        const srt = val.toString()
        return srt.replace(',', ' ~ ')
      } else {
        return ''
      }
    }
  },
  created () {
    setTimeout(() => {
      this.loading = !this.loading
    }, 800)
  },
  methods: {
    // 新增
    newMember () {
      const length = this.data.length
      this.data.push({
        key: length === 0 ? '1' : (parseInt(this.data[length - 1].key) + 1).toString(),
        name: '',
        workId: '',
        department: '',
        probation: '',
        editable: true,
        isNew: true
      })
    },
    // 删除行
    remove (key) {
      const newData = this.data.filter((item) => item.key !== key)
      this.data = newData
    },
    // 行内编辑事件
    handleInputChange (value, key, column) {
      console.log(value)
      console.log(key)
      console.log(column)
      const newData = [...this.data]
      const target = newData.find((item) => key === item.key)
      if (target) {
        target[column] = value
        this.data = newData
      }
    },
    // 编辑row
    toggle (key) {
      const target = this.data.find((item) => item.key === key)
      console.log(target)
      target._originalData = { ...target }
      target.editable = !target.editable
      console.log(target)
    },
    // row保存
    saveRow (record) {
      this.memberLoading = true
      const { key, name, workId, department, entry } = record // 需要校验的必填字段
      if (!name || !workId || !department || !entry) {
        this.memberLoading = false
        this.$message.error('请填写完整信息。')
        return
      }
      // 模拟网络请求、卡顿 800ms, 不需要走接口，去掉即可
      new Promise((resolve) => {
        setTimeout(() => {
          resolve({ loop: false })
        }, 800)
      }).then(() => {
        const target = this.data.find((item) => item.key === key)
        // 上面一行最后的“key”是否应为“record.key”?
        target.editable = false
        target.isNew = false
        this.memberLoading = false
      })
      console.log(this.data)
    },
    // 取消
    cancel (key) {
      const target = this.data.find((item) => item.key === key)
      Object.keys(target).forEach((key) => {
        target[key] = target._originalData[key]
      })
      target._originalData = undefined
    }
  }
}
</script>

<style lang="less" scoped>
</style>
